package com.xjoyt.pay.controllers.seabluesky;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.xjoyt.pay.dto.CallbackResult;
import com.xjoyt.pay.dto.MerchantChannelRegister;
import com.xjoyt.pay.dto.OrderUrlResult;
import com.xjoyt.pay.dto.enums.PayType;
import com.xjoyt.pay.dto.params.CallbackParam;
import com.xjoyt.pay.dto.params.MerchantRateRegister;
import com.xjoyt.pay.dto.params.OrderAdapterParam;
import com.xjoyt.pay.payutil.HttpUtil;
import com.xjoyt.pay.payutil.MD5;
import com.xjoyt.pay.payutil.MapUtils;
import com.xjoyt.pay.vo.Order;

/**
 * demo适配器
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("seaBlueSky/scanCodeT0")
public class ScanCodeT0Controller {
	public static String url = "http://121.196.196.167:8889/tran/";// 服务器地址

	/**
	 * 商户进件
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("register")
	public MerchantChannelRegister register(@RequestBody MerchantRateRegister param) {
		MerchantChannelRegister result = new MerchantChannelRegister();
		result.no = "17082200001868";
		result.key = "EF8217135E0D7299FCBC708370667AFC";
		return result;
	}

	/**
	 * 微信 向上游发起订单，前置条件订单信息已验证、订单已保存
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("wechatScan")
	public OrderUrlResult wechatScan(String no, String keyp, String orgNo, @RequestBody OrderAdapterParam param) {
		OrderUrlResult orderUrlResult = new OrderUrlResult();
		String key = keyp;
		String appId = no;
		String ORG_NO = orgNo;
		String out_trade_no = param.order.no; // 商户订单号
		String total_fee = param.order.money + ""; // 总金额
		String frontUrl = param.order.orderConfig.successUrl;// 同步通知地址;
		String notify_url = param.order.orderConfig.notifyUrl;// 异步通知地址
		String goodsName = param.order.merchantName;
		String tranType = "";
		if (PayType.WECHAT_SCAN.equals(param.payChannel.payType)) {
			tranType = "0402";
		} else if (PayType.ALIPAY_SCAN.equals(param.payChannel.payType)) {
			tranType = "0502";
		} else {
			orderUrlResult.success = false;
			return orderUrlResult;
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String action = "cashier/pay.ac";// 下单或支付;
		paramMap.put("version", "2.1");
		paramMap.put("orgNo", ORG_NO);
		paramMap.put("custId", appId);
		paramMap.put("custOrderNo", out_trade_no);
		paramMap.put("payAmt", total_fee);// 交易金额 分
		paramMap.put("frontUrl", frontUrl);
		paramMap.put("backUrl", notify_url);
		paramMap.put("tranType", tranType);
		paramMap.put("bankCode", "CMB");// 招行
		paramMap.put("goodsName", goodsName);// 商品名称
		paramMap.put("buyIp", "120.24.9.5");
		paramMap.put("sign", sign(paramMap, key));
		try {
			String resStr = HttpUtil.httpPost(url + action, paramMap);
			JSONObject jsonObject = JSONObject.parseObject(resStr);
			String codeURL = jsonObject.getString("busContent");
			if (!StringUtils.isEmpty(codeURL)) {
				orderUrlResult.url = codeURL;// 支付地址，生成二维码
				orderUrlResult.success = true;
				return orderUrlResult;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		orderUrlResult.success = false;
		return orderUrlResult;
	}

	public static String sign(Map<String, Object> paramMap, String signKey) {
		String signStr = MapUtils.getSignStrByTreeMap(paramMap, true);
		signStr += "&key=" + signKey;
		String signValue = MD5.sign(signStr, "UTF-8").toUpperCase();
		return signValue;
	}

	/**
	 * 支付宝 向上游发起订单，前置条件订单信息已验证、订单已保存
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("aliScan")
	public OrderUrlResult aliScan(String no, String keyp, String orgNo, @RequestBody OrderAdapterParam param) {
		return this.wechatScan(no, keyp, orgNo, param);
	}

	/**
	 * 回调
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("callback")
	public CallbackResult callback(String key, @RequestBody CallbackParam param) {
		CallbackResult result = new CallbackResult();
		result.success = false;
		result.callbackResponse = "FAIL";
		String appkey = key;// 商户密钥
		Map<String, Object> dataMap = new HashMap<>();
		if (param.params != null) {
			for (Entry<String, String[]> entry : param.params.entrySet()) {
				if (entry.getValue() == null || entry.getValue().length <= 0) {
					continue;
				}
				dataMap.put(entry.getKey(), entry.getValue()[0]);
			}
		}
		String sgin = (String) dataMap.get("sign");
		String prdOrdNo = (String) dataMap.get("prdOrdNo");
		dataMap.remove("sign");
		if (sgin.equals(sign(dataMap, appkey))) {// 验签成功就算回调成功
			result.success = true;
			result.tradeNo = prdOrdNo;
			result.callbackResponse = "SUCCESS";
		}
		return result;
	}

	/**
	 * 结算状态查询
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("settlement")
	public OrderUrlResult settlement(String type, @RequestBody Order param) {
		OrderUrlResult orderUrlResult = new OrderUrlResult();
		if (!StringUtils.isEmpty(type)) {
			if (type.equals("T0")) {
				orderUrlResult.success = true;
				return orderUrlResult;
			}
		}
		orderUrlResult.success = false;
		return orderUrlResult;
	}
}
